package com.hpjz.emrecord.service.impl;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import com.hpjz.common.utils.DateUtil;
import com.hpjz.emrecord.bean.GpsInfoBean;
import com.hpjz.emrecord.dao.GpsInfoDao;
import com.hpjz.emrecord.service.IGpsInfoService;
import com.hpjz.emrecord.web.vo.GpsInfoVO;

@Service("gpsInfoService")
public class GpsInfoServiceImpl implements IGpsInfoService{

	@Resource
	private GpsInfoDao gpsInfoDao; 
	
	@Override
	public Long insertGpsInfo(GpsInfoVO vo) {
		GpsInfoBean bean = this.voToBean(vo);
		//查询该车牌号的记录。并根据时间排序。
		 
		/*GpsInfoBean rbean = this.gpsInfoDao.findOne(bean);*/
		 List<GpsInfoBean> gpsInfos = this.gpsInfoDao.findList(bean);
		 int rcount = gpsInfos.size();
		 
		if (rcount==2) {
		    //将最小时间那一条设置。
			bean.setGpsid(gpsInfos.get(1).getGpsid());
			this.gpsInfoDao.update(bean);
		}else if(rcount<2){
			this.gpsInfoDao.insert(bean);
		}
		return null;
	}
	
	
	/**
	 * 将vo转化为bean
	 * @param vo
	 * @return
	 */
	private GpsInfoBean voToBean(GpsInfoVO vo){
		GpsInfoBean bean = new GpsInfoBean();
		BeanUtils.copyProperties(vo, bean);
		bean.setLasttime(new Date());
		if (StringUtils.isNotBlank(vo.getRecordid())) {
			bean.setRecordid(Long.valueOf(vo.getRecordid()));
		}
		return bean;
	}


	@Override
	public GpsInfoVO findCarPosition(GpsInfoVO vo) {
		GpsInfoBean bean = this.voToBean(vo);
		GpsInfoBean gbean = this.gpsInfoDao.findOne(bean);
		GpsInfoVO gvo = null;
		if (gbean!=null) {
			 gvo = this.beanToVO(gbean);
		}
		return gvo;
	}

    /**
     * 将bean转化为vo
     * @param gbean
     * @return
     */
	private GpsInfoVO beanToVO(GpsInfoBean gbean) {
		GpsInfoVO vo = new GpsInfoVO();
			BeanUtils.copyProperties(gbean, vo);
			vo.setRecordid(String.valueOf(gbean.getRecordid()));
			vo.setGpsid(String.valueOf(gbean.getGpsid()));
			vo.setLasttime(DateUtil.dateToStr(gbean.getLasttime()));
		return vo;
	}
 
}
